package com.hnit.controllers;

import com.hnit.service.CouponService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hnit.web.Utils.ResponseResult;
import com.hnit.web.bean.Coupons;
import com.hnit.web.bean.UserCoupons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 优惠券控制器
 */
@RestController
@RequestMapping("/coupon")
@Slf4j
public class CouponController {

    @Autowired
    private CouponService couponService;

    /**
     * 获取可抢购的优惠券列表
     * GET /product/coupon/list
     */
    @GetMapping("/list")
    public ResponseEntity<ResponseResult> getCouponsList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status) {

        try {
            IPage<Coupons> pageResult = couponService.getCouponsList(page, size, status);
            return ResponseEntity.ok(ResponseResult.ok().setData(pageResult));
        } catch (Exception e) {
            log.error("获取优惠券列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error("获取优惠券列表失败"));
        }
    }
    /**
     * 创建优惠券
     * POST /product/coupon/create
     */
    @PostMapping("/create")
    public ResponseEntity<ResponseResult> createCoupon(@RequestBody Coupons coupon) {
        try {
            couponService.createCoupon(coupon);
            return ResponseEntity.ok(ResponseResult.ok("优惠券创建成功"));
        } catch (Exception e) {
            log.error("创建优惠券失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error("创建优惠券失败"));
        }
    }

    /**
     * 获取所有的优惠券
     */
    /**
     * 管理员获取所有优惠券列表（带筛选条件）
     * GET /product/coupon/all
     *
     * @param page 页码，默认1
     * @param size 每页数量，默认10
     * @param couponName 优惠券名称关键词搜索
     * @param couponType 优惠券类型：1-满减券 2-折扣券
     * @param couponStatus 优惠券状态：1-正常 2-已过期 3-已停用
     * @param minAmount 最小金额筛选
     * @param maxAmount 最大金额筛选
     * @param startTime 开始时间筛选（YYYY-MM-DD格式）
     * @param endTime 结束时间筛选（YYYY-MM-DD格式）
     * @param sortBy 排序字段：createTime, amount, endTime等
     * @param sortOrder 排序方式：asc-升序 desc-降序
     * @return 优惠券分页列表
     */
    @GetMapping("/all")
    public ResponseEntity<ResponseResult> getAllCoupons(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String couponName,
            @RequestParam(required = false) Integer couponType,
            @RequestParam(required = false) Integer couponStatus,
            @RequestParam(required = false) BigDecimal minAmount,
            @RequestParam(required = false) BigDecimal maxAmount,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder) {

        try {
            // 参数校验
            if (page < 1) page = 1;
            if (size < 1 || size > 100) size = 10;

            // 调用服务层查询
            IPage<Coupons> result = couponService.getAllCouponsWithConditions(
                    page, size, couponName, couponType, couponStatus,
                    minAmount, maxAmount, startTime, endTime, sortBy, sortOrder
            );

            return ResponseEntity.ok(ResponseResult.ok().setData(result));

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.error("查询优惠券列表失败：" + e.getMessage()));
        }
    }

    /**
     * 抢购优惠券
     * POST /product/coupon/grab
     */
    @PostMapping("/grab")
    public ResponseEntity<ResponseResult> grabCoupon(
            @RequestBody Map<String, Long> params,
            @RequestHeader("X-User-ID") Long userId) {

        try {
            Long couponId = params.get("couponId");

            if (userId == null) {
                return ResponseEntity.ok(ResponseResult.error("请先登录"));
            }

            if (couponId == null) {
                return ResponseEntity.ok(ResponseResult.error("优惠券ID不能为空"));
            }

            boolean success = couponService.grabCoupon(userId, couponId, null);

            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("抢购成功！"));
            } else {
                return ResponseEntity.ok(ResponseResult.error("抢购失败"));
            }
        } catch (Exception e) {
            log.error("抢购优惠券失败", e);
            return ResponseEntity.ok(ResponseResult.error("抢购失败"));
        }
    }

    /**
     * 获取用户优惠券列表
     * GET /product/coupon/user/list
     */
    @GetMapping("/user/list")
    public ResponseEntity<ResponseResult> getUserCoupons(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestHeader("X-User-ID") Long userId) {

        try {
            if (userId == null) {
                return ResponseEntity.ok(ResponseResult.error("请先登录"));
            }

            IPage<UserCoupons> pageResult = couponService.getUserCoupons(userId, page, size, status);
            return ResponseEntity.ok(ResponseResult.ok().setData(pageResult));
        } catch (Exception e) {
            log.error("获取用户优惠券列表失败", e);
            return ResponseEntity.ok(ResponseResult.error("获取用户优惠券列表失败"));
        }
    }

    /**
     * 检查用户是否可以抢购某个优惠券
     * GET /product/coupon/check/{couponId}
     */
    @GetMapping("/check/{couponId}")
    public ResponseEntity<ResponseResult> checkCouponGrab(
            @PathVariable Long couponId) {

        try {
            // 简化检查逻辑，只检查优惠券本身的状态
            // 用户相关的检查在实际抢购时进行
            Coupons coupon = couponService.getCouponDetail(couponId);

            if (coupon == null || coupon.getCouponStatus() != 1) {
                return ResponseEntity.ok(ResponseResult.error("优惠券不存在或已下架"));
            }

            java.time.LocalDateTime now = java.time.LocalDateTime.now();
            if (now.isBefore(coupon.getStartTime())) {
                return ResponseEntity.ok(ResponseResult.error("活动未开始"));
            }
            if (now.isAfter(coupon.getEndTime())) {
                return ResponseEntity.ok(ResponseResult.error("活动已结束"));
            }

            if (coupon.getRemainingCount() <= 0) {
                return ResponseEntity.ok(ResponseResult.error("优惠券已抢完"));
            }

            return ResponseEntity.ok(ResponseResult.ok("可以抢购"));

        } catch (Exception e) {
            log.error("检查抢券资格失败", e);
            return ResponseEntity.ok(ResponseResult.error("检查失败"));
        }
    }

    /**
     * 获取优惠券详情
     * GET /product/coupon/detail/{couponId}
     */
    @GetMapping("/detail/{couponId}")
    public ResponseEntity<ResponseResult> getCouponDetail(@PathVariable Long couponId) {

        try {
            Coupons coupon = couponService.getCouponDetail(couponId);

            if (coupon != null) {
                return ResponseEntity.ok(ResponseResult.ok().setData(coupon));
            } else {
                return ResponseEntity.ok(ResponseResult.error("优惠券不存在"));
            }
        } catch (Exception e) {
            log.error("获取优惠券详情失败，ID: {}", couponId, e);
            return ResponseEntity.ok(ResponseResult.error("获取优惠券详情失败"));
        }
    }

    /**
     * 获取订单可用优惠券列表
     * GET /product/coupon/available
     */
    @GetMapping("/available")
    public ResponseEntity<ResponseResult> getAvailableCouponsForOrder(
            @RequestParam Double totalAmount,
            @RequestParam(required = false) String productIds,
            @RequestHeader("X-User-ID") Long userId) {

        try {
            if (userId == null) {
                return ResponseEntity.ok(ResponseResult.error("请先登录"));
            }

            // 解析商品ID列表
            List<Long> productIdList = null;
            if (productIds != null && !productIds.isEmpty()) {
                productIdList = java.util.Arrays.stream(productIds.split(","))
                        .map(String::trim)
                        .map(Long::parseLong)
                        .collect(java.util.stream.Collectors.toList());
            }

            List<UserCoupons> availableCoupons = couponService.getAvailableCouponsForOrder(
                    userId, totalAmount, productIdList);

            return ResponseEntity.ok(ResponseResult.ok().setData(availableCoupons));
        } catch (Exception e) {
            log.error("获取可用优惠券列表失败", e);
            return ResponseEntity.ok(ResponseResult.error("获取可用优惠券列表失败"));
        }
    }

    /**
     * 使用优惠券
     * POST /product/coupon/use
     */
    @PostMapping("/use")
    public ResponseEntity<ResponseResult> useCoupon(
            @RequestBody Map<String, Object> params,
            @RequestHeader("X-User-ID") Long userId) {

        try {
            String couponCode = (String) params.get("couponCode");
            Long orderId = Long.parseLong(params.get("orderId").toString());

            if (userId == null) {
                return ResponseEntity.ok(ResponseResult.error("请先登录"));
            }

            if (couponCode == null || couponCode.isEmpty()) {
                return ResponseEntity.ok(ResponseResult.error("优惠券码不能为空"));
            }

            if (orderId == null) {
                return ResponseEntity.ok(ResponseResult.error("订单ID不能为空"));
            }

            boolean success = couponService.useCoupon(userId, couponCode, orderId);

            if (success) {
                return ResponseEntity.ok(ResponseResult.ok("优惠券使用成功"));
            } else {
                return ResponseEntity.ok(ResponseResult.error("优惠券使用失败"));
            }
        } catch (Exception e) {
            log.error("使用优惠券失败", e);
            return ResponseEntity.ok(ResponseResult.error("使用优惠券失败"));
        }
    }

    /**
     * 获取用户优惠券统计信息
     * GET /product/coupon/user/stats
     */
    @GetMapping("/user/stats")
    public ResponseEntity<ResponseResult> getUserCouponStats(@RequestHeader("X-User-ID") Long userId) {

        try {
            if (userId == null) {
                return ResponseEntity.ok(ResponseResult.error("请先登录"));
            }

            int[] stats = couponService.getUserCouponStats(userId);

            // 封装统计结果
            Map<String, Integer> statsMap = new java.util.HashMap<>();
            statsMap.put("unused", stats[0]);    // 未使用
            statsMap.put("used", stats[1]);      // 已使用
            statsMap.put("expired", stats[2]);   // 已过期

            return ResponseEntity.ok(ResponseResult.ok().setData(statsMap));
        } catch (Exception e) {
            log.error("获取用户优惠券统计失败", e);
            return ResponseEntity.ok(ResponseResult.error("获取统计信息失败"));
        }
    }

    /**
     * 预热优惠券缓存（管理员接口）
     * POST /product/coupon/admin/warmup/{couponId}
     */
    @PostMapping("/admin/warmup/{couponId}")
    public ResponseEntity<ResponseResult> warmUpCouponCache(@PathVariable Long couponId) {

        try {
            // 这里可以添加管理员权限检查

            couponService.warmUpCouponCache(couponId);
            return ResponseEntity.ok(ResponseResult.ok("预热缓存成功"));
        } catch (Exception e) {
            log.error("预热优惠券缓存失败，ID: {}", couponId, e);
            return ResponseEntity.ok(ResponseResult.error("预热缓存失败"));
        }
    }

    /**
     * 同步Redis库存到数据库（管理员接口）
     * POST /product/coupon/admin/sync-stock/{couponId}
     */
    @PostMapping("/admin/sync-stock/{couponId}")
    public ResponseEntity<ResponseResult> syncStockToDatabase(@PathVariable Long couponId) {

        try {
            // 这里可以添加管理员权限检查

            couponService.syncStockToDatabase(couponId);
            return ResponseEntity.ok(ResponseResult.ok("同步库存成功"));
        } catch (Exception e) {
            log.error("同步库存失败，ID: {}", couponId, e);
            return ResponseEntity.ok(ResponseResult.error("同步库存失败"));
        }
    }

    /**
     * 批量更新过期优惠券（定时任务接口）
     * POST /product/coupon/admin/update-expired
     */
    @PostMapping("/admin/update-expired")
    public ResponseEntity<ResponseResult> updateExpiredCoupons() {

        try {
            // 这里可以添加管理员权限检查

            int updateCount = couponService.updateExpiredCoupons();
            return ResponseEntity.ok(ResponseResult.ok("更新完成").setData(updateCount));
        } catch (Exception e) {
            log.error("批量更新过期优惠券失败", e);
            return ResponseEntity.ok(ResponseResult.error("更新失败"));
        }
    }

    // ========== 私有方法 ==========

    /**
     * 获取当前登录用户ID
     * 这里需要根据您的认证方式来实现
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            // 方案一：从JWT Token中获取
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 解析JWT获取用户ID
                // 这里需要您实现JWT解析逻辑
                // return JwtUtil.getUserIdFromToken(token);
            }

            // 方案二：从Session中获取
            Object userId = request.getSession().getAttribute("userId");
            if (userId != null) {
                return Long.parseLong(userId.toString());
            }

            // 方案三：从Header中获取（临时测试用）
            String userIdHeader = request.getHeader("userId");
            if (userIdHeader != null) {
                return Long.parseLong(userIdHeader);
            }

            return null;
        } catch (Exception e) {
            log.error("获取用户ID失败", e);
            return null;
        }
    }
}
